const dgram = require("dgram");
const fs = require("fs");
const path = require("path");
const express = require("express");
const server = dgram.createSocket("udp4");

// 创建UDP服务器来接收摄像头数据
server.on('error', (err) => {
    // console.error(`server error:\n${err.stack}`);
    console.log("发生错误!");
    console.log(err);
    server.close();
});
// 用16进制打印一个uint8数组
function printUint8ArrByHex(arr) {
    for (let i = 0; i < arr.length; i++) {
        console.log(arr[i].toString(16));
    }
}
// 把一个uint8数组转换成string
function uint8ArrToString(arr) {
    let res = "";
    for (let i = 0; i < arr.length; i++) {
        res += String.fromCharCode(arr[i]);
    }
    return res;
}
let IMG;
let recFlag = 0;//记录接收状态
server.on('message', (msg, rinfo) => {
    let uint8Arr = new Uint8Array(msg);//先转uint8Array
    if (uint8Arr[0] == 0xFF && uint8Arr[1] == 0xD8) {
        // console.log("数据头!");
        // 开始记录
        recFlag = 1;
        // 充值数组
        IMG = new Uint8Array(uint8Arr);
        return;
    }
    if (recFlag == 0) return;
    // 合并上次的和这次的
    let temp = new Uint8Array(IMG.length + uint8Arr.length);
    temp.set(IMG);
    temp.set(uint8Arr, IMG.length);
    IMG = new Uint8Array(temp);
    // 判断是不是尾数据包
    if (uint8Arr[uint8Arr.length - 2] == 0xFF && uint8Arr[uint8Arr.length - 1] == 0xD9) {
        // console.log(IMG);//打印最终数组
        // console.log("数据尾!");
        // let str = uint8ArrToString(IMG);//把uint8Arr转成String
        // 把图片写到本地文件
        fs.writeFile(path.join(__dirname, "public", "stream.jpg"), IMG, (err) => {
            if (err) { console.log("文件写入失败!") }
        });
        recFlag = 0;
    }

});
server.on('listening', () => {
    const address = server.address();
    console.log(`server listening ${address.address}:${address.port}`);
});

server.bind(8000);

// 创建一个web服务器来显示图片
const app = express();
app.use(express.static("public"));
app.listen(80, () => {

});